<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use think\response\Json;
use app\api\model\User as UserModel;
use app\api\model\UserCoupon as UserCouponModel;
use app\api\service\User as UserService;
use cores\exception\BaseException;
use think\facade\Db;
use app\common\library\helper;

/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 当前用户详情
     * @return Json
     * @throws BaseException
     */
    public function info(): Json
    {
        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser(true);
        // 获取用户头像
        $userInfo['avatar'];
        // 获取会员等级
        $userInfo['grade'];
        //我选中的运动爱好
        $userInfo['hobby_my'] =$userInfo['hobby']? explode(",", $userInfo['hobby']):'' ;
        //查询是否第一次完善信息
        $sql = "SELECT * from java_task_record where user_phone =  ".$userInfo['mobile'].";";
        $list =Db::query($sql);
        if(empty($list)){
            $userInfo['is_first'] = 1;
        }else{
            $userInfo['is_first'] = 0;
        }
        $sql1 = "select * from yoshop_hobby order by id asc";
        $hobbylist =Db::query($sql1);
        $hobbylist = array_column($hobbylist,'name');
        array_push($hobbylist, "其他(可填写)");
        $userInfo['hobbylist'] = $hobbylist;

        return $this->renderSuccess(compact('userInfo'));
    }

    /**
     * 账户资产
     * @return Json
     * @throws BaseException
     */
    public function assets(): Json
    {
        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser(true);
        // 用户优惠券模型
        $model = new UserCouponModel;

        //商城积分+任务积分等于会员可用总积分
        $total_points = 0; //可使用积分
        $cumulative_energy = 0;  //总能量
        $sql = "SELECT b.points as shop_points, IF (( a.user_integral is NULL ), '0', a.user_integral ) AS `task_points` from yoshop_user b LEFT JOIN java_user_phone a on a.user_phone = b.mobile where b.mobile = ".$userInfo['mobile'].";";
        $list =Db::query($sql);
        if($list){
            $total_points =helper::bcadd($list[0]['shop_points'],$list[0]['task_points'],'0');
        }
        //获取我的总能量
          $httpApiUrl = $this->app->config->get('app.httpApiUrl');
        // 获取header请求中的token
        $java_token = $this->request->header('Authorization');
        $header  = array(
            'Authorization:'. $java_token,
        );
        $url = $httpApiUrl."api/getEnergy";
        $res =  json_decode(b5curl_get($url,$header),true);
        if(isset($res['code']) && $res['code']==200){
            $cumulative_energy =  isset($res['data'])?$res['data']:'0';
        }

        //获取我的等级
         $gradeImage = '';
         $gradeName = '';
         $nextGradeImage = '';
         $nextGradeName = '';
         $url1 = $httpApiUrl."api/getGrade";
         $rest=  json_decode(b5curl_get($url1,$header),true);
         if(isset($rest['data']) && $rest['code']==200){
            $gradeImage = $rest['data']['gradeImage']?$rest['data']['gradeImage']:'';
            $gradeName = $rest['data']['gradeName']? $rest['data']['gradeName']:'';
            $nextGradeImage = isset($rest['data']['nextGradeImage']) ?$rest['data']['nextGradeImage']:'';
            $nextGradeName = isset($rest['data']['nextGradeName'])? $rest['data']['nextGradeName']:'';
         }
      
        // 返回数据
        return $this->renderSuccess([
            'assets' => [
                'balance' => $userInfo['balance'],  // 账户余额
                // 'points' => $userInfo['points'],    // 会员积分
                'points' => $total_points,    // 会员积分(可用)
                'coupon' => $model->getCount($userInfo['user_id']),    // 优惠券数量(可用)
                'cumulative_energy' => $cumulative_energy,    // 累计能量
                'gradeImage' => $gradeImage,    // 等级图片
                'gradeName' => $gradeName,    // 等级名称
                'nextGradeImage' => $nextGradeImage,    // 等级名称
                'nextGradeName' => $nextGradeName,    // 等级名称
            ]
        ]);
    }

    /**
     * 手机号绑定
     * @return Json
     * @throws \cores\exception\BaseException
     */
    public function bindMobile(): Json
    {
        $model = new UserModel;
        if (!$model->bindMobile($this->postForm())) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('恭喜您，手机号绑定成功');
    }

    /**
     * 修改个人信息（头像昵称）
     * @return Json
     * @throws \cores\exception\BaseException
     */
    public function personal(): Json
    {   
        $model = new UserModel;
        $post = $this->postForm();
        if(isset($post['type']) && $post['type'] == 1){
            if(!isset($post['user_name']) || $post['user_name'] == ""){
                return $this->renderError($model->getError() ?: '请填写姓名');
            }

            if(!isset($post['gender']) || $post['gender'] == "0"){
                return $this->renderError($model->getError() ?: '请选择性别');
            }

            if(!isset($post['birthday']) || $post['birthday'] == ""){
                return $this->renderError($model->getError() ?: '请选择出生日期');
            }

            if(!isset($post['hobby']) || $post['hobby'] == ""){
                return $this->renderError($model->getError() ?: '请选择或填写运动爱好');
            }
        }
        if (!$model->personal($post)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
     
        if(isset($post['type']) && $post['type'] == 1){ //个人中心修改加积分 ,头像修改不加积分
            //任务完成添加积分
            $httpApiUrl = $this->app->config->get('app.httpApiUrl');
            // 获取header请求中的token
            $java_token = $this->request->header('Authorization');
            $header  = array(
                'Authorization:'. $java_token,
            );
            $url = $httpApiUrl."api/updateGrade?id=1";
            $res =  json_decode(b5curl_get($url,$header),true);
            if(isset($res['code']) && $res['code']==200){
                return $this->renderSuccess(array('status'=>1),'恭喜您，信息完善成功,任务已完成');
            }else{
                return $this->renderSuccess(array('status'=>0),'恭喜您，信息修改成功');
            }
        }else{
            return $this->renderSuccess(array('status'=>0),'恭喜您，信息修改成功');
        }
        
    }
}
